<!-- 查看指定ID的文章（用于进行预览和查看），下发显示操作按钮（根据文章状态和用户显示提交审核、审核通过、审核不通过、撤回等） -->
<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerArticleViewAndOperateModal"
    :title="modalTitle"
    :default-fullscreen="true"
    :minHeight="400"
    cancelText="关闭"
    :show-ok-btn="false"
    @cancel="onArticleViewAndOperateModalClose"
  >
    <!-- 使用slot在footer中添加自定义按钮 -->
    <template #insertFooter>
      <Tag v-if="articleFlag === 0 || articleFlag === '0'" color="default">
        当前文章状态为：草稿
      </Tag>
      <Tag v-else-if="articleFlag === 1 || articleFlag === '1'" color="warning">
        当前文章状态为：待审核
      </Tag>
      <Tag v-else-if="articleFlag === 2 || articleFlag === '2'" color="success">
        当前文章状态为：审核通过
      </Tag>
      <Tag v-else-if="articleFlag === 3 || articleFlag === '3'" color="error">
        当前文章状态为：审核未通过
      </Tag>
      <Tag v-else-if="articleFlag === 4 || articleFlag === '4'" color="success">
        当前文章状态为：已发布
      </Tag>
      <Tag v-else-if="articleFlag === 5 || articleFlag === '5'" color="warning">
        当前文章状态为：发布撤回
      </Tag>
      <Tag v-else-if="articleFlag === 9 || articleFlag === '9'" color="default">
        当前文章状态为：已删除
      </Tag>
      <Tag v-else> 当前文章状态为：{{ articleFlag }} </Tag>
      <!-- 查看文章操作日志 -->
      <a-button type="default" @click="onViewArticleLogsClick">查看文章操作日志</a-button>
      <!-- 不同状态文字的可用操作如下(文章管理)： -->
      <!-- 提交审核：草稿-0、发布撤回-5 -->
      <!-- 无任何操作：待审核-1、审核通过-2、审核未通过-3、已发布-4、已删除-9 -->
      <a-button
        v-if="
          type === 'drafting' &&
          (articleFlag == 0 || articleFlag == '0' || articleFlag == 5 || articleFlag == '5')
        "
        type="primary"
        @click="onSubmmitAuditArticleClick"
        >提交审核</a-button
      >
      <!-- 不同状态文字的可用操作如下(文章审核)： -->
      <!-- 审核通过、审核不通过：待审核-1 -->
      <!-- 发布、审核不通过：审核通过-2 -->
      <!-- 审核通过：审核未通过-3 -->
      <!-- 发布撤回：已发布-4 -->
      <!-- 发布：发布撤回-5 -->
      <!-- 无任何操作：草稿-0、已删除-9 -->
      <a-button
        v-if="
          type === 'audit' &&
          (articleFlag == 1 || articleFlag == '1' || articleFlag == 3 || articleFlag == '3')
        "
        type="primary"
        color="success"
        @click="onPassArticleClick"
        >审核通过</a-button
      >
      <a-button
        v-if="
          type === 'audit' &&
          (articleFlag == 1 || articleFlag == '1' || articleFlag == 2 || articleFlag == '2')
        "
        type="primary"
        color="error"
        @click="onNoPassArticleClick"
        >审核不通过</a-button
      >
      <a-button
        v-if="
          type === 'audit' &&
          (articleFlag == 2 || articleFlag == '2' || articleFlag == 5 || articleFlag == '5')
        "
        type="primary"
        color="success"
        @click="onPulishArticleClick"
        >发布</a-button
      >
      <a-button
        v-if="type === 'audit' && (articleFlag == 4 || articleFlag == '4')"
        type="primary"
        color="warning"
        @click="onRecallArticleClick"
        >发布撤回</a-button
      >
    </template>
    <div class="cms-article-container">
      <h1 class="cms-article-title">
        {{ article.title }}
      </h1>
      <h1 class="cms-article-subtitle">
        <a-space size="large">
          <span v-if="article.author != undefined && article.author != null && article.author != ''"
            >作者： {{ article.author }}</span
          >
          <span v-if="article.indept != undefined && article.indept != null && article.indept != ''"
            >部门： {{ article.indept }}</span
          >
          <span v-if="article.source != undefined && article.source != null && article.source != ''"
            >来源： {{ article.source }}</span
          >

          <span v-if="article.reviewuser && article.auditcount == 2">
            二审： {{ article.reviewuser }}
          </span>

          <span>发布时间： {{ article.intm }}</span>
          <span>浏览次数： {{ article.count }}</span>
        </a-space>
      </h1>
      <a-divider style="border-color: #ccc" dashed />
      <div v-if="article.ctype == 1" class="cms-article-content" v-html="article.content"> </div>
      <div v-else-if="article.ctype == 2" class="vditor-preview">
        <div v-html="showdownConverter.makeHtml(article.content || '')" class="vditor-reset"></div>
      </div>
      <div v-else-if="article.ctype == 3" class="cms-article-content"
        ><a :href="article.content" target="_blank">
          {{ article.content }}
        </a>
      </div>
      <CmsArticleFiles
        v-if="!!article.attachment && article.attachment.length > 0x0"
        :values="article.attachment"
      />
    </div>
    <ArticleOperate @register="registerArticleOperateForm" @success="onArticleOperateSuccess" />
    <ArticleLogs @register="registerArticleLogsViewForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, reactive, onBeforeMount, onUnmounted, computed } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { Divider, Tag } from 'ant-design-vue';

  import { useGlobSetting } from '/@/hooks/setting';

  import showdown from 'showdown';
  import 'vditor/dist/index.css';

  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { replaceAll } from '/@/utils/QcUnifyUtil';

  import { ArticleDto } from '/@/api/cms/model/articleModel';
  import { submmitArticle, passArticle, publishArticle, getArticle } from '/@/api/cms/article';

  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();

  import CmsArticleFiles from './../CmsArticleFiles.vue';
  import ArticleOperate from './ArticleOperate.vue';
  import ArticleLogs from './ArticleLogs.vue';
  import {
    getImageFileApi,
    getFileApi,
    uploadImageFileViewUrlPrefix,
    uploadVideoFileViewUrlPrefix,
  } from '/@/api/platform/file';

  export default defineComponent({
    name: 'CmsArticleViewAndOperate',
    components: {
      CmsArticleFiles,
      Divider,
      Tag,
      BasicModal,
      ArticleOperate,
      ArticleLogs,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { uploadUrl } = useGlobSetting();
      //弹出窗口界面是新增数据、修改数据还是重新处理数据；根据传递过来的参数进行判断
      const op = ref(OperationTypeEnum.PREVIEW);
      const moduleName = ref<string>('模块名称');
      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');
      //是从文章起草还是文章审核进入的该界面
      const type = ref<string>('');
      //文章的状态标记，根据状态标记不同下方显示的操作按钮不同
      const articleFlag = ref<number | string | undefined>();
      //记录在当前界面中是否对文章状态进行过变更
      const hasArticleFlagChanged = ref<boolean>(false);

      const showdownConverter = new showdown.Converter();
      showdownConverter.setOption('tables', true);

      const articleId = ref<string | number>();
      const articleTitle = ref<string>('');
      const article = ref<ArticleDto>({});

      const [registerArticleViewAndOperateModal, { setModalProps, closeModal }] = useModalInner(
        async (data) => {
          //根据传递过来的参数获取对应的操作，操作不同所对应的界面不同
          //接收父组件传递的数据
          if (data?.articleId) {
            articleId.value = data.articleId;
            getArticleDetail(articleId.value);
          }
          if (data?.moduleName) {
            moduleName.value = data.moduleName;
          }
          if (moduleName) {
            modalTitle.value = unref(moduleName);
          }
          modalTitle.value += '--' + op.value;
          //文章的状态标记
          if (data?.articleFlag) {
            articleFlag.value = data.articleFlag;
          }
          //触发的模块，是文章起草还是文章审核
          // console.log('CmsArticleViewAndOperate props.type', data.type);
          if (data?.type === 'audit') {
            type.value = data.type;
          }
          // console.log('CmsArticleViewAndOperate type.value', type.value);

          setModalProps({ confirmLoading: false });
        },
      );
      const [registerArticleOperateForm, { openModal: openArticleOperateForm }] = useModal();
      const [registerArticleLogsViewForm, { openModal: openArticleLogsViewForm }] = useModal();

      //获取文章详情信息
      function getArticleDetail(articleId) {
        getArticle({ id: articleId }).then((res) => {
          // console.log('getArticleDetail res', res);
          article.value = res;
          //将文章内容中的图片和视频url前缀进行替换还原
          let articleContent = res.content;
          if (
            articleContent != undefined &&
            articleContent != null &&
            articleContent.length > 0x0
          ) {
            articleContent = replaceAll(
              articleContent,
              uploadImageFileViewUrlPrefix + getImageFileApi,
              uploadUrl + getImageFileApi,
            );
            articleContent = replaceAll(
              articleContent,
              uploadVideoFileViewUrlPrefix + getFileApi,
              uploadUrl + getFileApi,
            );
          }
          article.value.content = articleContent;
          //获取到文章信息后对标题进行赋值，方便后面直接使用
          articleTitle.value = res.title;
        });
      }

      /**
       * 提交审核
       */
      function onSubmmitAuditArticleClick() {
        submmitArticle({ id: articleId.value })
          .then((res) => {
            if (!res) {
              //操作成功后修改文章状态标记，以便于界面中显示的按钮及时更新
              articleFlag.value = 1;
              createMessage.success('提交审核成功，请等待审核。', 2);
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 审核通过
       */
      function onPassArticleClick() {
        passArticle({ id: articleId.value })
          .then((res) => {
            if (!res) {
              //操作成功后修改文章状态标记，以便于界面中显示的按钮及时更新
              //后台流程处理中审核通过后状态为已发布-4，直接跳过审核通过-2
              // articleFlag.value = 2;
              articleFlag.value = 4;
              createMessage.success('审核通过完成，已发布', 2);
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 审核不通过
       */
      function onNoPassArticleClick() {
        openArticleOperateForm(true, {
          op: OperationTypeEnum.CUSTOME,
          operateType: 3,
          moduleName: modalTitle.value,
          dataId: articleId.value,
          articleTitle: articleTitle.value,
        });
      }

      /**
       * 发布
       */
      function onPulishArticleClick() {
        publishArticle({ id: articleId.value })
          .then((res) => {
            if (!res) {
              //操作成功后修改文章状态标记，以便于界面中显示的按钮及时更新
              articleFlag.value = 4;
              createMessage.success('发布文章成功。', 2);
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 发布撤回
       */
      function onRecallArticleClick() {
        openArticleOperateForm(true, {
          op: OperationTypeEnum.CUSTOME,
          operateType: 5,
          moduleName: modalTitle.value,
          dataId: articleId.value,
          articleTitle: articleTitle.value,
        });
      }

      /**
       * 文章操作成功--用于更新文章状态
       */
      function onArticleOperateSuccess(data) {
        //根据不同的操作类型设置文章的状态标记
        //操作类型：审核不通过-3、发布撤回-5
        if (!data) {
          //打开的modal中没有传递参数，不进行处理
          console.log('onArticleOperateSuccess data', data);
        } else {
          if (data === 3 || data === '3') {
            //审核不通过-3
            articleFlag.value = 3;
          } else if (data === 5 || data === '5') {
            //发布撤回-5
            articleFlag.value = 5;
          } else {
            console.log('onArticleOperateSuccess data', data);
          }
        }
      }

      /**
       * 查看文章操作日志
       */
      function onViewArticleLogsClick() {
        openArticleLogsViewForm(true, {
          op: OperationTypeEnum.LOG,
          moduleName: modalTitle.value,
          dataId: articleId.value,
          articleTitle: articleTitle.value,
        });
      }

      /**
       * 点击Modal中的关闭/取消按钮事件
       */
      async function onArticleViewAndOperateModalClose() {
        //判断是否对文章进行操作，操作后才需要调用父组件中的成功事件进行表格数据刷新
        closeModal();
        if (!!hasArticleFlagChanged.value) {
          //如果文章状态发送变化，调用父组件中的事件进行表格刷新；如果文章状态没有变化不需要刷新
          emit('success');
        }
      }

      onBeforeMount(() => {
        // console.log('CmsArticleViewAndOperate onBeforeMount');
      });
      onUnmounted(() => {
        // console.log('CmsArticleViewAndOperate onUnmounted');
      });

      return {
        op,
        moduleName,
        modalTitle,
        type,
        articleFlag,
        articleId,
        articleTitle,
        article,
        hasArticleFlagChanged,
        showdownConverter,
        getArticleDetail,
        registerArticleViewAndOperateModal,
        registerArticleOperateForm,
        registerArticleLogsViewForm,
        onSubmmitAuditArticleClick,
        onPassArticleClick,
        onNoPassArticleClick,
        onPulishArticleClick,
        onRecallArticleClick,
        onViewArticleLogsClick,
        onArticleOperateSuccess,
        onArticleViewAndOperateModalClose,
      };
    },
    watch: {
      articleFlag: function (newVal, oldVal) {
        console.log('watch articleFlag oldVal=' + oldVal + ' newVal=' + newVal);
        //如果oldVal为空表示没有进行赋初值，本次数据值变化不进行判断
        if (!oldVal) {
          console.log('watch articleFlag oldVal为空，本次为初始化赋值。');
        } else {
          this.hasArticleFlagChanged = true;
        }
      },
    },
  });
</script>
<style scoped lang="less">
  @import './../cms.less';
</style>
